
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<%@page import="kyakya.User"%>
<%@page import="kyakya.manager.DBManager"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.awt.ItemSelectable"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="java.io.File"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>

<!DOCTYPE html>
<%@include file="header.jsp" %>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="css/style-form.css" id="style" rel="stylesheet" type="text/css"></link>
    <title>JSP Page</title>
</head>
<!-- BODY -->
<%@include file="functions.jsp" %>

<!-- login test-->
<%--<c:set var="username" scope="page" value="harton" />--%>

<%--<c:remove var="user"/>--%>

<c:choose>
    <c:when test="${cookie.username !=null}">
        <!--uda login-->        

    </c:when>
    <c:otherwise>        
        <!-- belum login-->
        <%
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                System.out.println("Registration : Mulai menerima input form");
                // is multipart    
                HashMap<String, String> userData = new HashMap<String, String>();
                FileItem avatarFile = null;

                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                List items;
                try {
                    items = upload.parseRequest(request);
                    Iterator itr = items.iterator();
                    boolean valid = true;
                    StringBuilder errMsgBuilder = new StringBuilder();
                    while (itr.hasNext()) {
                        FileItem item = (FileItem) itr.next();
                        if (item.isFormField()) {
                            // form field..semua di inputkan dulu
                            if (!item.getString().equals("")) {
                                userData.put(item.getFieldName(), item.getString());
                            } else if (item.getFieldName().equals("about")) {
                                userData.put(item.getFieldName(), item.getString());
                            } else {
                                valid = valid && false;
                                errMsgBuilder.append(item.getFieldName() + " tidak boleh kosong <br/>");
                                userData.put(item.getFieldName(), "");
                            }
                            out.println(item.getFieldName() + " : " + userData.get(item.getFieldName()) + " <br/>");
                        } else {
                            // file avatar yang diupload                            
                            if (item.getName().equals("")) {
                                // avatar belum diupload                                
                                valid = valid && false;
                                errMsgBuilder.append("avatar tidak boleh kosong <br/>");
                            } else {
                                // valid
                                userData.put(item.getFieldName(), "/upload/avatar/" + userData.get("username"));
                                avatarFile = item;
                            }
                            out.println(item.getFieldName() + " : " + userData.get(item.getFieldName()) + " <br/>");
                        }
                    }
                    // validasi isi field
                    if (valid) {
                        System.out.println("Registration : semua field terisi");
                        // semua field terisi
                        // check username                        
                        if (userData.get("username").length() > 4) {
                            // regex username
                        } else {
                            // username notvalid
                            errMsgBuilder.append("username invalid <br/>");
                            errMsgBuilder.append(' ');
                            valid = valid && false;
                        }

                        if (userData.get("password").length() > 7) {
                        } else {
                            // password invalid
                            errMsgBuilder.append("password invalid <br/>");
                            valid = valid && false;
                        }

                        if (userData.get("password").equals(userData.get("confirmpassword"))) {
                        } else {
                            // invalid
                            errMsgBuilder.append("password dan confirm password harus sama <br/>");
                            valid = valid && false;
                        }

                        // cek username
                        if (Pattern.matches("^[A-Za-z0-9_.]{5,}$", userData.get("username"))) {
                            
                        } else {
                            errMsgBuilder.append("usernaame tidak valid <br/>");
                            valid = valid && false;
                        }

                        // cek email
                        if (Pattern.matches("[0-9a-zA-Z\\.]+@[a-zA-Z]+\\.[a-zA-Z]{2,}", userData.get("email"))) {
                            
                        } else {
                            errMsgBuilder.append("email tidak valid <br/>");
                            valid = valid && false;
                        }

                        // cek tanggal
                        if (Pattern.matches("^[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}[ ]*$", userData.get("tanggal"))) {
                            
                        } else {
                            errMsgBuilder.append("tanggal tidak valid <br/>");
                            valid = valid && false;
                        }

                        // cek nama
                        if (Pattern.matches("^[A-Za-z0-9]+[ ]+[A-Za-z0-9]+.*$",userData.get("nama"))) {
                            
                        } else {
                            errMsgBuilder.append("nama tidak valid <br/>");
                            valid = valid && false;
                        }


                        // cek password
                        if (Pattern.matches("^[A-Za-z0-9_]{8,}", userData.get("password"))) {
                            
                        } else {
                            errMsgBuilder.append("password tidak valid <br/>");
                            valid = valid && false;
                        }

                        // cek avatar
                        if (avatarFile != null){
                            if (getExtension(avatarFile.getName()).equals("jpg") || getExtension(avatarFile.getName()).equals("jpeg")){                                
                                
                            }else{
                                errMsgBuilder.append("ekstensi avatar tidak valid <br/>");
                                valid = valid && false;
                            }
                        }else{
                            valid = valid && false;
                        }
                        
                        if (valid) {
                            System.out.println("Registration : isi field sesuai");
                            // field sesuai                           
                            User user = DBManager.getUserByUsername(userData.get("username"));
                            if (user == null) {
                                // username baru valid
                                System.out.println("Registration : username yang ingin didaftarkan valid");
                            } else {
                                errMsgBuilder.append("Cari username lain <br/>");
                                System.out.println("Registration : username yang ingin didaftarkan tidak valid");
                                valid &= false;
                            }

                            User userbyemail = DBManager.getUserByEmail(userData.get("email"));
                            if (userbyemail == null) {
                                System.out.println("Registration : email yang diinginkan valid");
                            } else {
                                errMsgBuilder.append("Cari email lain <br/>");
                                valid &= false;
                                System.out.println("Registration : email yang diinginkan tidak valid");
                            }

                            if (valid) {
                                System.out.println("Registration : semua isi field valid");
                                User newUser = new User();
                                newUser.setUsername(userData.get("username"));
                                newUser.setAbout(userData.get("about"));
                                newUser.setAvatarPath(userData.get("avatar"));
                                newUser.setBirthday(userData.get("tanggal"));
                                newUser.setEmail(userData.get("email"));
                                if (userData.get("gender").equals("Laki-laki")) {
                                    newUser.setGender("1");
                                } else {
                                    newUser.setGender("0");
                                }
                                newUser.setName(userData.get("nama"));
                                newUser.setPassword(userData.get("password"));

                                if (DBManager.insertNewUser(newUser)) {
                                    // memastikan folder avatar
                                    System.out.println("Registration : Query insert user berhasil");
                                    System.out.println("Registration : " + newUser);
                                    File avatarFolder = new File(config.getServletContext().getRealPath("/") + "/upload/avatar/");
                                    if (!avatarFolder.exists()) {
                                        avatarFolder.mkdirs();
                                    }
                                    File avatarPath = new File(avatarFolder + "/" + newUser.getUsername());
                                    if (avatarFile != null) {
                                        avatarFile.write(avatarPath);
                                        System.out.println("Registration : file avatar berhasil diupload");
                                    } else {
                                        System.out.println("Registration : file avatar null");
                                    }

                                } else {
                                    // penambahan user gagal                                                                        
                                    System.out.println("Registration : Query insert user gagal");
                                    valid &= false;
                                }

                            } else {
                                // username atau email sudah ada yang punya
                                System.out.println("Registration : username atau email sudah ada yang punya");
                            }

                            // konek ke database
                            // cek username unique atau tidak

                        } else {
                            // isi field tidak sesuai
                            System.out.println("Registration : isi field tidak sesuai");
                        }// end if isi field sesuai

                    } else {
                        // tidak semua field terisi  
                        System.out.println("Registration : tidak semua field terisi");
                    }// end if field tidak terisi


                    // validasi selesai, sekarang navigasi
                    if (valid) {
                        // register sukses                        
                        System.out.println("Registration : Registrasi success, redirect ke index.jsp");
                        response.sendRedirect("index.jsp");
                    } else {
                        // register gagal                                                     
                        System.out.println("Registration : Registrasi gagal");

        %>
        <form enctype='multipart/form-data' action='registration.jsp' method='post'>			
            <div class='form_box'>
                <h1>Registrasi Pengguna</h1>
                <label> <!-- username field -->
                    <span id='username_span' class='spanvalid' >Username</span>
                    <input type='text' class='text' name='username' value="<% out.println(userData.get("username"));%>"/><br />			
                </label>			
                <label><!-- password field -->
                    <span id='password_span' class='spanvalid'>Password</span>
                    <input type='password' name='password' class='text'/><br />
                </label>					
                <label><!-- password confirm field -->
                    <span id='confirm_span' class='spanvalid'>Confirm Password</span>
                    <input type='password' name='confirmpassword' class='text'/><br />
                </label>					
                <label><!-- nama field -->
                    <span id='nama_span' class='spanvalid'>Nama Lengkap</span>
                    <input type='text' class='text' name='nama' value="<% out.println(userData.get("nama"));%>"/><br />
                </label>		
                <label><!-- tanggal field -->
                    <span id='tanggal_span' class='spanvalid'>Tanggal Lahir</span>
                    <input type='text' class='text' name='tanggal' value="<% out.println(userData.get("tanggal"));%>"/><br />
                </label>		
                <label><!-- gender field -->
                    <span id='gender_span' class='spanvalid'>Jenis Kelamin</span>
                    <select name='gender' class='text' id='gender' >
                        <option></option>
                        <option selected="<% if (userData.get("gender").equals("Laki-laki")) {
                                out.println("selected");
                            }%>">Laki-laki</option>
                        <option selected="<% if (userData.get("gender").equals("Perempuan")) {
                                out.println("selected");
                            }%>">Perempuan</option>
                    </select>
                </label>

                <label><!-- email field -->
                    <span id='email_span' class='spanvalid'>Email</span>
                    <input type='text' class='text' name='email' value="<% out.println(userData.get("email"));%>"/><br />
                </label>
                <label><!-- avatar field -->
                    <span id='avatar_span' class='spanvalid'>Avatar</span>
                    <input name='avatar' class='text' type='file' accept='image/JPEG' />
                </label>		
                <label><!-- about field and button-->
                    <span  class='spanvalid'>About Me</span>
                    <textarea  name='about' class='about' rows='5' cols='40'><% out.println(userData.get("about"));%></textarea><br />
                    <input type='submit' class='buttonenabled' value='Daftar' id='daftar' />
                </label>			
            </div>
        </form>  

        <%
                    // registrasi gagal
                    out.println(errMsgBuilder.toString());
                }// end if of proses registrasi                    
            } catch (Exception e) {
                System.out.println("Registration : Exception");
                e.printStackTrace();
                System.out.println("Registration : end of exception");
            }

        } else {
        %>

        <!--belum submit form-->
        <form enctype='multipart/form-data' action='registration.jsp' method='post'>			
            <div class='form_box'>
                <h1>Registrasi Pengguna</h1>
                <label> <!-- username field -->
                    <span id='username_span' class='spanvalid' >Username</span>
                    <input type='text' class='text' name='username' /><br />			
                </label>			
                <label><!-- password field -->
                    <span id='password_span' class='spanvalid'>Password</span>
                    <input type='password' name='password' class='text'/><br />
                </label>					
                <label><!-- password confirm field -->
                    <span id='confirm_span' class='spanvalid'>Confirm Password</span>
                    <input type='password' name='confirmpassword' class='text'/><br />
                </label>					
                <label><!-- nama field -->
                    <span id='nama_span' class='spanvalid'>Nama Lengkap</span>
                    <input type='text' class='text' name='nama' /><br />
                </label>		
                <label><!-- tanggal field -->
                    <span id='tanggal_span' class='spanvalid'>Tanggal Lahir</span>
                    <input type='text' class='text' name='tanggal' /><br />
                </label>		
                <label><!-- gender field -->
                    <span id='gender_span' class='spanvalid'>Jenis Kelamin</span>
                    <select name='gender' class='text' id='gender' >
                        <option></option>
                        <option>Laki-laki</option>
                        <option>Perempuan</option>
                    </select>
                </label>

                <label><!-- email field -->
                    <span id='email_span' class='spanvalid'>Email</span>
                    <input type='text' class='text' name='email' /><br />
                </label>
                <label><!-- avatar field -->
                    <span id='avatar_span' class='spanvalid'>Avatar</span>
                    <input name='avatar' class='text' type='file' accept='image/JPEG' />
                </label>		
                <label><!-- about field and button-->
                    <span  class='spanvalid'>About Me</span>
                    <textarea  name='about' class='about' rows='5' cols='40'></textarea><br />
                    <input type='submit' class='buttonenabled' value='Daftar' id='daftar' />
                </label>			
            </div>
        </form>  

        <%            }
        %>
    </c:otherwise>
</c:choose>




<!-- /BODY -->   
<%@include file="footer.jsp" %>